package com.zxp.utils.fileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FileUnzipper {

    /**
     * Unzips the specified zip file to the specified destination directory.
     *
     * @param zipFilePath          The path of the zip file to unzip.
     * @param destinationDirectory The path of the directory to unzip the zip file to.
     */
    public static void unzip(String zipFilePath, String destinationDirectory) {
        byte[] buffer = new byte[1024];
        try (ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(Paths.get(zipFilePath)))) {
            // create output directory if it doesn't exist
            File destDir = new File(destinationDirectory);
            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            // iterate through each entry in the zip file
            ZipEntry zipEntry = zipInputStream.getNextEntry();
            while (zipEntry != null) {
                String entryName = zipEntry.getName();
                File entryFile = new File(destinationDirectory + File.separator + entryName);
                // create directories if the entry is a directory
                if (zipEntry.isDirectory()) {
                    entryFile.mkdirs();
                } else {
                    // create parent directories if they don't exist
                    new File(entryFile.getParent()).mkdirs();

                    // write the file content
                    try (FileOutputStream fos = new FileOutputStream(entryFile)) {
                        int len;
                        while ((len = zipInputStream.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                // move to the next entry
                zipInputStream.closeEntry();
                zipEntry = zipInputStream.getNextEntry();
            }
            System.out.println("File unzipped successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // Example usage:
        String zipFilePath = "B:\\download\\downloadedFile.zip";
        String destinationDirectory = "B:\\download\\test";
        unzip(zipFilePath, destinationDirectory);
    }
}
